package com.example.demo.weixin;

import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * 微信模板消息接口（给某个用户发送消息）
 *
 * @version 1.0.0.0
 * @auhtor 崔少良 2018/6/4 0004
 */
public class Test {
    private static final Logger logger = Logger.getLogger(Test.class.getSimpleName());

    public static void main(String[] args) {
        boolean bl = sendTemplate("2Hfho88xQZbNL-7mriy8Nh5ERB-2WrDHz4P3DT4MRtY","ohxSm03BMRYoPcYRt55eYYjg09tc","wxa990232fa0581173","8b79488320ad5464b2ad991b26044ba0");
    }
    /**
     * TODO
     *
     * @author Create by 崔少良 2018-06-05 上午 9:10
     * @param: templateId 模板id
     * @param: toUser 用户openID
     * @param: appid 微信公众号的appid
     * @param: appsecret 微信公众号的appsecret
     * @return boolean 发送是否成功
     */
    public static boolean sendTemplate(String templateId, String toUser, String appid, String appsecret){
        Template tem = new Template();
        tem.setTemplateId(templateId);//模板id
        tem.setTopColor("#00DD00");
        tem.setToUser(toUser);//用户openID
        tem.setUrl("http://weixin.qq.com");//具体地址(http://weixin.qq.com)为详情页面  ""为没有详情项

        List<TemplateParam> paras = new ArrayList<TemplateParam>();
        paras.add(new TemplateParam("first", "测试模板消息接口", "#FF3333"));
        paras.add(new TemplateParam("orderMoneySum", "测试价格", "#0044BB"));
        paras.add(new TemplateParam("orderProductName", "测试商品名称", "#6644AA"));
        paras.add(new TemplateParam("Remark", "感谢!!!!", "#AAAAAA"));
        tem.setTemplateParamList(paras);
        //自己的APPID和APPsecret
        Token token = CommonUtil.getToken(appid, appsecret);
        boolean bl = sendTemplateMsg(token.getAccessToken(), tem);//返回值为true或false
        return bl;
    }

    public static boolean sendTemplateMsg(String token, Template template) {
        boolean flag = false;
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        System.out.println("ACCESS_TOKEN:"+token);
        requestUrl = requestUrl.replace("ACCESS_TOKEN", token);

        JSONObject jsonResult = CommonUtil.httpsRequest(requestUrl, "POST", template.toJSON());
        if (jsonResult != null) {
            int errorCode = jsonResult.getInt("errcode");
            String errorMessage = jsonResult.getString("errmsg");
            if (errorCode == 0) {
                flag = true;
                System.out.println("模板消息发送成功:" + errorCode + "," + errorMessage);
            } else {
                System.out.println("模板消息发送失败:" + errorCode + "," + errorMessage);
                flag = false;
            }
        }
        return flag;
    }
}
